package cn.feizhu.aimarket.ai.service.impl;

import cn.feizhu.aimarket.ai.client.WriterChatClientFactory;
import cn.feizhu.aimarket.ai.service.AiService;
import cn.feizhu.aimarket.service.BookService;
import jakarta.annotation.Resource;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.ai.chat.client.ChatClient;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.CompletableFuture;

@Service
public class AiServiceImpl implements AiService {

    private static final Logger logger = LoggerFactory.getLogger(AiServiceImpl.class);

    @Resource
    private WriterChatClientFactory writerChatClientFactory;

    @Resource
    private BookService bookService;

    // TODO 后期需要智能体判断是否包含链接然后读取链接
    // TODO 后期需要添加知识库等更好搜索
    // TODO 后期需要有一个生成目录的AI异步处理
    @Override
    public String generatePages(Long userId, Long appId, String userMessage, Integer parallelNum) {
        // 快速检查快速失败
        if (userMessage == null || userMessage.trim().isEmpty()) {
            throw new IllegalArgumentException("User message cannot be null or empty");
        }
        if (parallelNum <= 0 || parallelNum >= 10) {
            throw new IllegalArgumentException("Parallel number must be greater than zero and less than 10");
        }

        ChatClient chatClient = writerChatClientFactory.createWriterChatClient();

        // 创建一个列表来存储所有的CompletableFuture
        List<CompletableFuture<String>> futures = new ArrayList<>();

        // 创建所有异步任务
        for (int i = 0; i < parallelNum; i++) {
            final int taskIndex = i + 1; // 从1开始编号
            CompletableFuture<String> futureTask = CompletableFuture.supplyAsync(() -> {
                try {
                    logger.info("开始生成第{}篇文章，userId={}, appId={}", taskIndex, userId, appId);
                    String indexedUserMessage = String.format("这是第%d篇文章，请根据以下内容进行创作：%s, appId=%s, userId=%s", taskIndex, userMessage, appId, userId);

                    String response = chatClient.prompt().user(indexedUserMessage).call().chatResponse().getResult().getOutput().toString();
                    logger.info("第{}篇文章生成完成，内容长度: {} 字符", taskIndex, response.length());
                    return response;
                } catch (Exception e) {
                    logger.error("生成第{}篇文章时发生异常: {}", taskIndex, e.getMessage(), e);
                    // 根据异常类型提供更具体的错误信息
                    if (e.getMessage().contains("timeout") || e.getMessage().contains("Read timed out")) {
                        logger.warn("第{}篇文章生成超时，可能是网络问题或AI服务响应慢", taskIndex);
                        return "生成超时，请稍后重试";
                    } else if (e.getMessage().contains("RestClientException")) {
                        logger.warn("第{}篇文章生成时API调用失败: {}", taskIndex, e.getMessage());
                        return "API调用失败，请检查网络连接";
                    } else {
                        return "生成失败: " + e.getMessage();
                    }
                }
            });

            futures.add(futureTask);
        }

        try {
            // 等待所有任务完成
            CompletableFuture<Void> allTasks = CompletableFuture.allOf(futures.toArray(new CompletableFuture[0]));
            allTasks.join(); // 阻塞等待所有任务完成

            // 统计成功和失败的任务数量
            long successCount = 0;
            long failureCount = 0;

            for (CompletableFuture<String> future : futures) {
                try {
                    String result = future.join();
                    if (result != null && !result.startsWith("生成超时") && !result.startsWith("API调用失败") && !result.startsWith("生成失败")) {
                        successCount++;
                    } else {
                        failureCount++;
                        logger.warn("任务失败，结果: {}", result);
                    }
                } catch (Exception e) {
                    failureCount++;
                    logger.error("获取任务结果时发生异常: {}", e.getMessage());
                }
            }

            logger.info("所有文章生成任务完成，成功: {}/{}, 失败: {}", successCount, parallelNum, failureCount);

            if (successCount == parallelNum) {
                return String.format("所有%d篇文章生成完成！", parallelNum);
            } else if (successCount > 0) {
                return String.format("文章生成完成，成功: %d篇，失败: %d篇。失败的任务可能由于网络超时或API限制导致。", successCount, failureCount);
            } else {
                return String.format("所有%d篇文章生成失败，请检查网络连接和API配置。", parallelNum);
            }

        } catch (Exception e) {
            logger.error("等待异步任务完成时发生错误: {}", e.getMessage());
            return "文章生成过程中发生错误: " + e.getMessage();
        }
    }




}
